package com.qifan.alb2b.util.diy;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.qifan.alb2b.exception.BusinessException;
import com.qifan.alb2b.exception.DataAccessException;


/**
 * 统一异常处理类，为所有的Controller抛出的异常提供一个统一的入口
 * 1.记录异常日志
 * 2.判断是否是ajax请求返回{"msg":"操作失败,业务出错了！","success":false}样式的json字符串
 * 2.转发错误处理页面
 * @author hjc
 * @version 2009-11-27
 */
public class MyHandlerExceptionResolver implements HandlerExceptionResolver {

	private static final Log logger=LogFactory.getLog(MyHandlerExceptionResolver.class);

	@SuppressWarnings("unchecked")
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		if(ex instanceof DataAccessException ||ex instanceof BusinessException)
			logger.info("发生数据库或者逻辑错误:" + ex.getMessage(),ex);//记录异常日志
		else
			logger.error("发生异常:" + ex.getMessage(),ex);//记录异常日志
		String httpAjax=request.getHeader("X-Requested-With");
		if(httpAjax!=null&&"XMLHttpRequest".equals(httpAjax)){//判断ajax请求
			PrintWriter out = null;
			try {
				response.setCharacterEncoding("utf-8");
				response.setContentType("application/json");
				out=response.getWriter();
				Map<String,Object> map = new HashMap();
				map.put("success", false);
				map.put("msg", "操作失败,"+ex.getMessage());
				ObjectMapper objectMapper=new ObjectMapper();
				JsonGenerator jsonGenerator=objectMapper.getJsonFactory().createJsonGenerator(out);
				jsonGenerator.writeObject(map);
			} catch (IOException e) { 
				e.printStackTrace();
			}finally{
				out.flush();
				out.close();
			}
			return null;
		}else{//非ajax请求
			if (ex instanceof MaxUploadSizeExceededException) {
				request.setAttribute("exception", "文件大小超过5M");
				request.setAttribute("stack", ex.toString());
			}else{
				request.setAttribute("exception", ex.getMessage());
				request.setAttribute("stack", ex.toString());
			}
			return new ModelAndView("pages/common/error");
		}
		
	}

}
